package com.minesweeper.tools;

import com.minesweeper.data.ImagesData;

import javax.sound.sampled.*;
import java.io.IOException;

/**
 * @author skniy
 */
public class BackgroundMusic implements Runnable {

    @Override
    public void run() {
        //循环播放音乐
        while (true) {
            //打开文件
            AudioInputStream audioInputStream = null;
            try {
                audioInputStream = AudioSystem.getAudioInputStream(ImagesData.MUSIC_BACKGROUND);
            } catch (UnsupportedAudioFileException | IOException e) {
                e.printStackTrace();
            }
            assert audioInputStream != null;
            AudioFormat audioFormat = audioInputStream.getFormat();
            SourceDataLine sourceDataLine = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            try {
                sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }
            try {
                assert sourceDataLine != null;
                sourceDataLine.open(audioFormat);
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }
            sourceDataLine.start();
            //播放音乐
            int nBytesRead = 0;
            byte[] abData = new byte[512];
            while (nBytesRead != -1) {
                try {
                    nBytesRead = audioInputStream.read(abData, 0, abData.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (nBytesRead >= 0) {
                    sourceDataLine.write(abData, 0, nBytesRead);
                }
            }
            //关闭SourceDataLine
            sourceDataLine.drain();
            sourceDataLine.close();
        }

    }


}
